<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="规则名称">
                <a-input allowClear placeholder="请输入规则名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList()">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList()">
          <a-radio-button v-for="item of statusList" :key="item.id" :value="item.id"> {{ item.name }} </a-radio-button>
        </a-radio-group>

        <div style="display: flex">
          <a-button type="primary" style="margin-right: 10px" @click="visible = true">+ 新增</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="handleAll('remove', '2')">批量删除</a-menu-item>
              <a-menu-item @click="handleAll('change', '1')" v-if="queryParam.status != '1'">批量开启</a-menu-item>
              <a-menu-item @click="handleAll('change', '0')" v-if="queryParam.status != '0'">批量关闭</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>

      <a-table
        :row-key="record => record.id"
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        :pagination="{
          total: this.totalCount,
          showSizeChanger: true,
          onChange: this.getList,
          onShowSizeChange: this.paginationSizeChange
        }"
        :data-source="list"
        :loading="loading"
        :columns="columns"
      >
        <span slot="rule" slot-scope="text, record">
          <a-tooltip>
            <template slot="title">
              {{ getArea(record.area) }}
            </template>
            <h4 class="over_e">{{ getArea(record.area) }}</h4>
          </a-tooltip>
        </span>

        <span slot="switch" slot-scope="text, record">
          <a-switch
            :checked="record.status === '1' ? true : false"
            checked-children="开"
            un-checked-children="关"
            @change="handleItem('change', record)"
          />
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleItem('edit', record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="handleItem('remove', record)" size="small">删除</a-button>
        </span>
      </a-table>

      <a-modal title="规则详情" @cancel="onClose" @ok="onSave" okText="保存" :destroyOnClose="true" :visible="visible">
        <a-row v-if="loading" style="text-align: center"><a-spin /></a-row>
        <template v-else>
          <a-row :gutter="[16, 30]" type="flex" align="middle">
            <a-col class="required" :span="5" style="text-align: right"> 规则名称： </a-col>
            <a-col :span="16">
              <a-input placeholder="请填写规则名称" v-model="postage.name" />
            </a-col>
          </a-row>
          <a-row :gutter="[16, 30]" type="flex" align="middle">
            <a-col :span="5" style="text-align: right"> 是否启用： </a-col>
            <a-col :span="16">
              <a-radio-group v-model="postage.status">
                <a-radio :value="1"> 开启 </a-radio>
                <a-radio :value="0"> 关闭 </a-radio>
              </a-radio-group>
            </a-col>
          </a-row>
          <a-row :gutter="[16, 30]" type="flex" align="top">
            <a-col :span="5" style="text-align: right"> 选择区域： </a-col>
            <a-col :span="16">
              <a-card
                v-for="(province, index) in province_list"
                size="small"
                :key="index"
                style="margin-bottom: 10px;max-height:500px;overflow-y:scroll"
              >
                <a-button slot="extra" size="small" @click="delProvince(index)">删除</a-button>
                <a-row type="flex">
                  <span
                    style="margin-right: 10px"
                    v-for="(item, index1) of province.province_list"
                    :key="index + '' + index1"
                  >
                    {{ item.name }}
                  </span>
                </a-row>
              </a-card>
              <a-button v-if="!province_list.length" @click="showInfoStatus = true" icon="plus" size="small">
                新增条目
              </a-button>
            </a-col>
          </a-row>
        </template>

        <a-modal v-model="showInfoStatus" v-if="district.length > 0" :width="700" title="添加运费规则" @ok="handleOk">
          <a-row>
            <a-tree
              style="display: flex; flex-wrap: wrap"
              :blockNode="true"
              :checkable="true"
              @check="e => onSelectCheck(e)"
              multiple
            >
              <a-tree-node
                :style="{ width: '33%', display: 'flex', flexWrap: 'wrap' }"
                v-for="province of district"
                :key="JSON.stringify({ id: province.id, name: province.name, type: 'province' })"
                :title="province.name"
              >
                <a-tree-node
                  v-for="city of province.children"
                  :isLeaf="true"
                  :key="JSON.stringify({ id: city.id, name: city.name, type: 'city' })"
                  :title="city.name"
                >
                </a-tree-node>
              </a-tree-node>
            </a-tree>
          </a-row>
        </a-modal>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { List, Save, Status } from '@/api/setting/salesRules'
import { areaList } from '@/api/marketing/alipayPromotion'

export default {
  data() {
    return {
      queryParam: {
        status: '',
        name: ''
      },

      labelCol: { span: 4 },
      wrapperCol: { span: 14 },

      postage: { name: '', status: 1 },

      list: [],
      selectedRowKeys: [],

      totalCount: 0,
      pageSize: 10,
      pageNo: 1,
      loading: false,
      visible: false,

      columns: [
        {
          title: '规则名称',
          dataIndex: 'name',
          key: 'name',
          width: 200,
          ellipsis: true
        },
        {
          title: '销售规则',
          ellipsis: true,
          scopedSlots: { customRender: 'rule' }
        },
        {
          title: '是否开启',
          width: 200,
          scopedSlots: { customRender: 'switch' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          width: 150
        }
      ],

      statusList: [
        { id: '', name: '全部' },
        { id: '1', name: '已开启' },
        { id: '0', name: '已关闭' }
      ],

      showInfoStatus: false, // 是否展示地区
      province_list: [],
      selectData: [],
      district: []
    }
  },

  computed: {
    getArea() {
      return area => {
        return area[0].province_list.map(el => el.name).join('/')
      }
    },

    getTitle() {
      return this.form.id ? '编辑规则' : '新增规则'
    }
  },

  methods: {
    // 分页器页数修改回调
    paginationSizeChange(current, size) {
      this.pageSize = size
      this.getList(current)
    },

    getList(pageNo = 1) {
      this.loading = true
      let { queryParam, pageSize } = this
      List({
        ...queryParam,
        pageNo,
        pageSize
      })
        .then(res => {
          this.loading = false

          if (!res.code) {
            this.pageNo = pageNo
            this.list = res.data.data
            return
          }

          this.$message.error(res.msg)
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 批量操作
    handleAll(type, status) {
      let selectedRowKeys = this.selectedRowKeys

      if (!selectedRowKeys.length) {
        return this.$message.error('请至少选择一条选项！')
      }

      selectedRowKeys = selectedRowKeys.join(',')
      switch (type) {
        case 'remove':
          this.Status(selectedRowKeys, status)
          break
        case 'change':
          this.Status(selectedRowKeys, status)
          break
      }
    },

    handleItem(type, scope) {
      switch (type) {
        case 'edit':
            this.postage = {
              name : scope.name,
              id:scope.id,
              status:parseInt(scope.status)
            }
            this.province_list = scope.area;
            this.visible = true
          break

        case 'remove':
          this.Status(scope.id, '2')
          break

        case 'change':
          this.Status(scope.id, scope.status === '1' ? '0' : '1')
          break
      }
    },

    Status(ids, status) {
      // 0.禁用 1.启用 2.删除
      Status({
        ids,
        status
      }).then(res => {
        if (!res.code) {
          this.$message.success('操作成功')
          this.selectedRowKeys = []
          this.getList()
          return
        }

        this.$message.error(res.msg)
      })
    },

    // 选中多行
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    delProvince(index) {
      this.province_list.splice(index, 1)
    },

    onSelectCheck(value) {
      var arr = []
      value.forEach(element => {
        if (JSON.parse(element).type === 'city') {
          arr.push(JSON.parse(element))
        }
      })
      this.selectData = arr
    },

    handleOk() {
      this.showInfoStatus = false
      var data = {
        province_list: this.selectData
      }
      this.province_list.push(data)
    },

    onClose() {
      this.visible = false
      this.loading = false
      this.province_list = []
      this.postage = { name: '', status: 1 }
    },

    onSave() {
      let { province_list: area, postage } = this

      if (!postage.name) {
        return this.$message.error('请填写规则名称！')
      }

      if (!area.length) {
        return this.$message.error('请选择区域！')
      }

      this.$message.loading({ content: '提交中', key: 'updatable' })

      Save({
        area: JSON.stringify(area),
        ...postage
      }).then(res => {
        if (res.code === 0) {
          this.$message.success({ content: res.msg, key: 'updatable' })

          this.$nextTick(() => {
            this.visible = false
            this.selectData = []
            this.province_list = []
            this.getList()
          })
        } else {
          this.$message.error({ content: res.msg, key: 'updatable' })
        }
      })
    }
  },

  created() {
    this.getList()

    areaList().then(res => {
      console.log('res,', res)
      if (!res.code) {
        this.district = res.data.area_code || []
      }
    })
  }
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;

  .slot {
    border: 1px solid #d9d9d9;
    border-left: 0;
    border-radius: 0 4px 4px 0;
    height: 32px;
    width: 32px;
    background: rgba(247, 247, 247, 1);
    text-align: center;
  }
}

.over_e {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
